package com.person.ntv.service.sys.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.person.common.PageParams;
import com.person.exception.ServiceException;
import com.person.ntv.dao.sys.SysResourceMapper;
import com.person.ntv.entity.sys.SysResource;
import com.person.ntv.entity.sys.SysRoleResource;
import com.person.ntv.service.base.impl.BaseServiceImpl;
import com.person.ntv.service.sys.CommonService;
import com.person.ntv.service.sys.SysResourceService;
import com.person.ntv.service.sys.SysRoleResourceService;
import com.person.ntv.service.sys.SysRoleService;
import com.person.ntv.shiro.util.ShiroFilterChainManager;
@Service("sysResourceService")
public class SysResourceServiceImpl extends BaseServiceImpl<SysResource> implements SysResourceService{
	@Autowired
	private SysResourceMapper sysResourceMapper;
	@Autowired
	private CommonService commonService;
	@Autowired
	private ShiroFilterChainManager shiroFilterChainManager;
	@Autowired
	private SysRoleResourceService sysRoleResourceService;
	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	   public void setBaseMapper(){
		   super.setBaseMapper(this.sysResourceMapper);
	   }
	
	@Override
	public Page<SysResource> getSysResources(PageParams pp) throws ServiceException {
	    try {
			PageHelper.startPage(pp.getPage(),pp.getRows(), pp.getOrderStr());
			return sysResourceMapper.getSysResources(pp.getParams());
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("系统错误！");
		}
	}

	@Override
	public List<Map<String, Object>> getMenuTree(Map<String,String> params) throws ServiceException {
		List<Map<String, Object>> srs;
		try {
			srs = sysResourceMapper.getMenuTree(params);
			return srs;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("系统错误！");
		}
	}

	@Override
	public int deleteByPrimaryKeys(BigDecimal[] ids) throws ServiceException {
		try{
			int result=0;
			SysRoleResource srr=new  SysRoleResource();
		    for(BigDecimal id:ids){
		    	result+=deleteByPrimaryKey(id);
		    	//删除关联表数据
		    	srr.setResourceId(id);
		    	sysRoleResourceService.delete(srr);
		    }
		    return result;
			}catch (Exception e) {
		          e.printStackTrace();
		          throw new ServiceException("系统错误。");
		  }
	}

	@Override
	public int validateResName(String resName, String id)
			throws ServiceException {
		try{
			Map<String,String>params=new HashMap<String,String>();
			params.put("id", id);
			params.put("resName",resName);
		    return   sysResourceMapper.validateResName(params);//commonService.validateOne("sys_resource","res_name",resName, id);
			}catch (Exception e) {
		          e.printStackTrace();
		          throw new ServiceException("系统错误。");
		  } 
	}

	@Override
	public int validateResCode(String resCode, String id)
			throws ServiceException {
		try{
			 return commonService.validateOne("sys_resource","res_code",resCode, id);
			}catch (Exception e) {
		          e.printStackTrace();
		          throw new ServiceException("系统错误。");
		  }
	}

	@Override
	public List<Map<String, Object>> getMenuTreeByRole(String roleIds)
			throws ServiceException {
		List<Map<String, Object>> srs;
		try {
			srs = sysResourceMapper.getMenuTreeByRole(roleIds);
			return srs;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("系统错误！");
		}
	}

	@Override
	public List<Map<String, Object>> getPageTreeByRole(String roleIds)
			throws ServiceException {
		List<Map<String, Object>> srs;
		try {
			srs = sysResourceMapper.getPageTreeByRole(roleIds);
			return srs;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("系统错误！");
		}
	}

	@Override
	public int updateProvision(String[] ids,String roleId,String type) throws ServiceException {
		try {
			if(ids==null||ids.length==0)return 0;
			List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
			List<Map<String,Object>> addList=new ArrayList<Map<String,Object>>();
			List<Map<String,Object>> deleteList=new ArrayList<Map<String,Object>>();
            if("menu".equals(type)){
            list.addAll(sysResourceMapper.getMenuTreeByRole(String.valueOf(roleId)));
            permissionCalc(ids, roleId, list, addList, deleteList);
            }else if("page".equals(type)){
			list.addAll(sysResourceMapper.getPageTreeByRole(String.valueOf(roleId)));
			 permissionCalc(ids, roleId, list, addList, deleteList);
            }else if("user".equals(type)){
            List<Map<String,Object>> userList=new ArrayList<Map<String,Object>>();
            Map<String,Object>map=null;
             for(String id:ids){
            	 if(id.split(",").length!=3)
            		 continue;
            	 map=new HashMap<String,Object>();
            	 map.put("userId",id.split(",")[2]);
            	 map.put("roleId",roleId);
            	 userList.add(map);
             }
             //删除角色对应的所有用户再重新添加
             sysRoleService.deleteRoleUsers(roleId);
             sysRoleService.addRoleUser(userList);
         }
            return addList.size()+deleteList.size();
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("系统错误！");
		}
	}
	
	 private void permissionCalc(String[] ids,String roleId,List<Map<String,Object>> list,List<Map<String,Object>> addList,List<Map<String,Object>> deleteList) throws Exception{
			Map<String,String> cMap=new HashMap<String,String>();
			Map<String,Object> addMap=null;
			Map<String,Object> deleteMap=null;
			//取交集
			for(String id:ids){
				for(Map<String,Object>map:list){
					if(map.get("checked").toString().equals("0"))
						continue;
					  if(String.valueOf(map.get("id")).equals(id)){
						cMap.put(String.valueOf(id),id);
						break;
					}
				}
			}
			for(String id:ids){
				if(!cMap.containsKey(id)){
					addMap =new HashMap<String,Object>();
					addMap.put("roleId", roleId);
					addMap.put("resourceId",id);
					addList.add(addMap);
				}
			}
			for(Map<String,Object>map:list){
				if(map.get("checked").toString().equals("0"))
					continue;
				  if(!cMap.containsKey(String.valueOf(map.get("id")))){
					  deleteMap =new HashMap<String,Object>();
					  deleteMap.put("roleId", roleId);
					  deleteMap.put("resourceId",Integer.valueOf(map.get("id").toString()));
					  deleteList.add(deleteMap);
				}
			}
			if(addList.size()>0)
				sysResourceMapper.addProvision(addList);
			if(deleteList.size()>0)
				sysResourceMapper.deleteProvision(deleteList);
			if(addList.size()>0||deleteList.size()>0)//更新权限 filterChain
				shiroFilterChainManager.initFilterChains(sysResourceMapper.getAllUrlFilter());
	 } 
}
